package com.sdy.hospitalguard.h5.controller;

import com.sdy.common.model.FileObj;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.OsPathUtil;
import com.sdy.hospitalguard.biz.constants.RedisConstants;
import com.sdy.hospitalguard.biz.utils.HttpReqUtil;
import com.sdy.hospitalguard.h5.vo.IdCardOcrObj;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author cgj
 * @since 2020/05/14
 */
@RestController
@RequestMapping("/distinguishIdCard")
@Api(tags = "身份证识别接口")
@Slf4j
public class ParseIdCardController extends BaseController {
    @Autowired
    private RedisService redisService;

    @GetMapping("/parseIdCard")
    @ResponseBody
    @ApiOperation(value = "身份证识别")
    @ApiImplicitParam(value = "文件ID", name = "fileId")
    public Response<IdCardOcrObj> parseIdCard(String fileId) throws Exception {
        FileObj fileObj = redisService.get(RedisConstants.FILE_UPLOAD_UUID + fileId, FileObj.class);
        Assert.isNull(fileObj, "上传的文件已过期，请重新上传。");
        File f = new File(OsPathUtil.convertWithOs(fileObj.getPath()));
        FilePart fp = new FilePart("image_file", f);
        Part[] parts = {fp};
        String jsonStr = HttpReqUtil.postMultipart(
                "http://trial.web.glority.cn:8000/classify?type=8",
                parts,
                StandardCharsets.UTF_8.name(),
                StandardCharsets.UTF_8.name(),
                3000, null);
        IdCardOcrObj result = JsonUtil.fromJson(jsonStr, IdCardOcrObj.class);
        return Response.success(result);
    }

}
